import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:huajianshe_app/base/BaseState.dart';
import 'package:huajianshe_app/common/load_image.dart';
import 'package:huajianshe_app/common/res.dart';
import 'package:huajianshe_app/network/Api.dart';
import 'package:huajianshe_app/network/response/BaseResp.dart';
import 'package:huajianshe_app/network/response/ResourceResp.dart';
import 'package:huajianshe_app/pages/main/PostPage.dart';
import 'package:huajianshe_app/pages/user_info/model/UserModel.dart';
import 'package:huajianshe_app/utils/dialog_util.dart';
import 'package:huajianshe_app/utils/toast_utils.dart';
import 'package:huajianshe_app/widget/AvatarWidget.dart';
import 'package:huajianshe_app/widget/RoundedCornerWidget.dart';
import 'package:huajianshe_app/widget/SimpleScrollView.dart';
import 'package:huajianshe_app/widget/SmartButton.dart';
import 'package:huajianshe_app/widget/appbar/CAppBar.dart';
import 'package:huajianshe_app/widget/dialog/SelectMediaBottomSheet.dart';
import 'package:image_picker/image_picker.dart';

class UserInfoEditPage extends StatefulWidget {

  final UserInfo? info;

  const UserInfoEditPage(this.info, {Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _UserInfoEditPageState();
  }
}

class _UserInfoEditPageState extends BaseState<UserInfoEditPage> {

  final TextEditingController nameController = TextEditingController();
  final TextEditingController mobileController = TextEditingController();
  final TextEditingController wechatController = TextEditingController();
  final TextEditingController emailController = TextEditingController();
  final TextEditingController companyController = TextEditingController();
  final TextEditingController positionController = TextEditingController();
  final TextEditingController introController = TextEditingController();
  MediaFileInfo? avatar;
  final _picker = ImagePicker();
  UserInfo? userInfo;

  @override
  void initState() {
    super.initState();
    avatar = MediaFileInfo(widget.info?.avatar ?? '', false, widget.info?.avatarId);
    nameController.text = widget.info?.realname ?? '';
    mobileController.text = widget.info?.mobile ?? '';
    wechatController.text = widget.info?.wechatNo ?? '';
    emailController.text = widget.info?.email ?? '';
    companyController.text = widget.info?.companyName ?? '';
    positionController.text = widget.info?.positionName ?? '';
    introController.text = widget.info?.desc ?? '';
    userInfo = widget.info;
  }

  @override
  void onReqSuccess<T>(T t, int code, String msg, String path) {
    if (t is UploadResp) {
      print('${t.data?.url}');
      if (t.data?.url != null) {
        avatar = MediaFileInfo(t.data!.url!, false, t.data!.id);
        setState(() => {});
      }
    } else if (t is BaseResp) {
      if (t.code == 0) {
        // data = CircleCreateInfo();
        // setState(() => null);
      }
      Toast.show(t.msg);
    }
  }

  @override
  Widget build(BuildContext context) {
    return
      Scaffold(
        appBar: CAppBar(title: '编辑资料', backImgUrl: 'ic_black_arrow', overlayStyle: SystemUiOverlayStyle.dark),
        backgroundColor: Colors.white,
        body: SimpleScrollView(
          padding: EdgeInsets.only(top: 10, left: 13, right: 13, bottom: 13),
          children: [
            H(13),
            Text('基础信息', style: TS(15, C.gray333)),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, radius: 0,
                child: Column(children: [
                  Padding(padding: EdgeInsets.symmetric(vertical: 15),
                      child: InkWell(onTap: () => { chooseAvatar() }, child: Row(children: [
                        Text('头像', style: TS(15, C.gray1A),),
                        Spacer(),
                        AvatarWidget(avatar?.path, 55, 0, 0),
                        W(10),
                        LoadImage('ic_gray_right_arrow')
                      ]))
                  ),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('用户姓名', style: TS(15, C.gray1A))),
                  Expanded(child: TextField(autofocus: false, controller: nameController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 12, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "最多8字", hintStyle: TS(14, C.grayC3))
                  )),
                  W(15),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('联系电话', style: TS(15, C.gray1A),)),
                  Expanded(child: TextField(autofocus: false, controller: mobileController, focusNode: null, keyboardType: TextInputType.number,
                      style: TS(14, C.gray1A), maxLength: 11, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "手机号", hintStyle: TS(14, C.grayC3))
                  )),
                  W(15),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('微信号', style: TS(15, C.gray1A))),
                  Expanded(child: TextField(autofocus: false, controller: wechatController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 20, decoration: new InputDecoration(
                        border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                        counterText: '', hintText: "请输入微信号", hintStyle: TS(14, C.grayC3))
                  )),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('邮箱', style: TS(15, C.gray1A))),
                  Expanded(child: TextField(autofocus: false, controller: emailController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 20, decoration: new InputDecoration(
                          border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                          counterText: '', hintText: "请输入个人邮箱", hintStyle: TS(14, C.grayC3))
                  )),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('公司名称', style: TS(15, C.gray1A))),
                  Expanded(child: TextField(autofocus: false, controller: companyController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 20, decoration: new InputDecoration(
                          border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                          counterText: '', hintText: "请输入公司名称", hintStyle: TS(14, C.grayC3))
                  )),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: 50, radius: 0,
                child: Row(children: [
                  SizedBox(width: 90, child: Text('所属职位', style: TS(15, C.gray1A))),
                  Expanded(child: TextField(autofocus: false, controller: positionController, focusNode: null,
                      style: TS(14, C.gray1A), maxLength: 20, decoration: new InputDecoration(
                          border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none,
                          counterText: '', hintText: "请输入所属职位", hintStyle: TS(14, C.grayC3))
                  )),
                ])
            ),
            PD(1, 15, 15),
            RoundedCornerWidget(backgroundColor: Colors.white, width: double.infinity, height: null, radius: 0,
                child: Column(children: [
                  H(15),
                  Row(children: [
                    Text('自我介绍', style: TS(15, C.gray1A),),
                  ]),
                  H(15),
                  TextField(autofocus: false, controller: introController, focusNode: null,
                    maxLines: 5, maxLength: 50,
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.only(left: 12, right: 12, top: 10, bottom: 10),
                      fillColor: C.grayF6,
                      filled: true,
                      border: new OutlineInputBorder(
                        borderSide: BorderSide.none,
                        borderRadius: const BorderRadius.all(Radius.circular(9.0)),
                      ),
                      hintStyle: TS(14, C.grayC3),
                      hintText: "请输入自我介绍",
                    ),
                  )
                ])
            ),
          ],
          bottomView: Padding(padding: EdgeInsets.symmetric(vertical: 17, horizontal: 27),
              child: SmartButton(width: double.infinity, height: 50, text: '保存', textColor: Colors.white,
                fontSize: 17, radius: 25, onPressed: submit)
          )
        ),
      );
  }

  submit() {
    widget.info?.avatarId = avatar?.id;
    widget.info?.realname = nameController.text;
    widget.info?.wechatNo = wechatController.text;
    widget.info?.mobile = mobileController.text;
    widget.info?.email = emailController.text;
    widget.info?.companyName = companyController.text;
    widget.info?.positionName = positionController.text;
    widget.info?.desc = introController.text;
    sendReq(Api.editUserInfo(), BaseResp(), data: widget.info?.toJson());
  }

  chooseAvatar() {
    DialogUtil.showBottomDialogV2(context, SelectMediaBottomSheet(
      includeVideo: false,
      onMediaResult: (isVideo, isCamera) {
        onMediaResult(isVideo, isCamera);
      },
    ), radius: 13, margin: EdgeInsets.symmetric(horizontal: 5));
  }

  void onMediaResult(bool isVideo, isCamera) async {
    var source = isCamera ? ImageSource.camera : ImageSource.gallery;
    final pickedFile = await _picker.getImage(source: source);
    if (pickedFile != null) {
      File file = File(pickedFile.path);
      uploadImage(file);
    }
  }

  uploadImage(File image) async {
    final String path = image.path;
    final String filename = path.substring(path.lastIndexOf('/') + 1);
    var file = await MultipartFile.fromFile(path, filename: filename);
    debugPrint('file:${file.filename.toString()}');
    sendReq(Api.uploadPic(), UploadResp(), data: {'file': file});
  }
}